<!-- 账号管理 -->
<template>
  <div id="template">
    <page-main>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="管理员" name="admin">
          <avue-crud
            v-model="Main_Form"
            :option="Main_Option"
            :data="Main_Data"
            :page.sync="Main_Page"
            :search.sync="Main_search"
            :table-loading="main_table_loading"
            ref="crud"
            @refresh-change="refreshChange"
            @search-change="searchChange"
            @reset-change="resetChange"
            @row-save="rowSave"
            @row-update="rowUpdate"
            @size-change="sizeChange"
            @current-change="currentChange"
            @row-del="rowDel"
          >
          </avue-crud>
        </el-tab-pane>

        <el-tab-pane label="前台用户" name="users">
          <avue-crud
            v-model="Main_Form"
            :option="Users_Option"
            :data="Users_Data"
            :page.sync="Users_Page"
            :search.sync="Users_search"
            :table-loading="users_table_loading"
            ref="crud"
            @refresh-change="refreshChange"
            @search-change="searchChange"
            @reset-change="resetChange"
            @row-save="rowSaveUsers"
            @row-update="rowUpdateUsers"
            @size-change="sizeChange"
            @current-change="currentChange"
            @row-del="rowDelUsers"
          >
            <!-- 头像插槽 -->
            <template v-slot:avatar="{ row }">
              <el-image
                v-if="row.avatar"
                :src="row.avatar"
                style="width: 50px; height: 50px;"
              ></el-image>
              <span v-else>暂无头像</span>
            </template>
            <template slot="menu" slot-scope="{ row }">
              <el-button type="text" size="small" @click="shoppingCart(row)"
                >购物车</el-button
              >
            </template>
          </avue-crud>
        </el-tab-pane>
      </el-tabs>
    </page-main>

    <!-- 购物车管理页面 -->
    <el-drawer
      title="用户购物车管理"
      :visible.sync="shoppingCartDrawer"
      :destroy-on-close="true"
      size="80%"
    >
      <page-main>
        <div>购物车商品明细</div>
        <avue-crud
          :option="Shoppingcart_Option"
          :data="Shoppingcart_Data"
          ref="product"
          :page.sync="Shoppingcart_Page"
          :search.sync="Shoppingcart_search"
          @search-change="searchShoppingChange"
          @refresh-change="refreshShoppingChange"
          @reset-change="resetShoppingChange"
          @size-change="sizeShoppingChange"
          @current-change="currentShoppingChange"
          @row-update="rowUpdatecart"
          @row-del="removeProducts"

        >
          <!-- 商品图插槽 -->
          <template v-slot:defaultImg="{ row }">
            <el-image
              v-if="row.defaultImg"
              :src="row.defaultImg"
              style="width: 50px; height: 50px;"
            ></el-image>
            <span v-else>暂无商品图</span>
          </template>
        </avue-crud>
      </page-main>
    </el-drawer>
  </div>
</template>

<script>
import {
  Main_Option,
  Main_Data,
  Users_Option,
  Users_Data,
  Shoppingcart_Option,
  Shoppingcart_Data,
} from "./config";
import {
  queryUsersInfoApi,
  createUsersInfoApi,
  updateUsersInfoApi,
  deleteUsersInfoApi,
  queryAdminInfoApi,
  createAdminInfoApi,
  updateAdminInfoApi,
  deleteAdminInfoApi,
} from "@/api/admin/index";

import {
  queryUsersCartApi,
  updateUsersCartApi,
} from "@/api/shoppingcartsManage/index";

export default {
  data() {
    return {
      //管理员信息
      Main_Option,
      Main_Data,
      main_table_loading: false,
      Main_Form: {},
      Main_search: {},
      Main_Page: {
        currentPage: 1,
        pageSize: 10,
        total: 1,
      },
      //用户信息
      activeName: "admin",
      Users_Option,
      Users_Data,
      users_table_loading: false,
      Users_search: {},
      Users_Page: {
        currentPage: 1,
        pageSize: 10,
        total: 1,
      },

      //活动商品
      Shoppingcart_Option,
      Shoppingcart_Data,
      Shoppingcart_table_loading: false,
      Shoppingcart_search: {},
      Shoppingcart_Page: {
        currentPage: 1,
        pageSize: 10,
        total: 1,
      },
      shoppingCartDrawer: false,
      usercartId: null,
      userId: null,
      productId: null,
      productNum: null,
    };
  },
  mounted() {
    this.getHomePageInfoFunc();
  },
  methods: {
    // 搜索事件
    async searchChange(params, done) {
      this.Main_Page.currentPage = 1;
      this.Main_Page.pageSize = 10;

      this.Users_Page.currentPage = 1;
      this.Users_Page.pageSize = 10;

      await this.getHomePageInfoFunc();
      done();
    },
    // 重置
    resetChange() {
      this.Main_search = {};
      this.Users_search = {};
    },
    // 刷新
    refreshChange() {
      this.Main_Page.currentPage = 1;
      this.Users_Page.currentPage = 1;
      this.getHomePageInfoFunc();
    },

    currentChange(val) {
      this.Main_Page.currentPage = val;
      this.Users_Page.currentPage = val;
      this.getHomePageInfoFunc();
    },

    sizeChange(val) {
      this.Main_Page.pageSize = val;
      this.Users_Page.pageSize = val;
      this.getHomePageInfoFunc();
    },
    //管理员信息新增
    rowSave(form, done, loading) {
      const { username, password, state } = form;

      this.createAdminInfoFunc({ username, password, state }, done, loading);
    },

    //用户信息新增
    rowSaveUsers(form, done, loading) {
      const {
        nickName,
        avatar,
        userName,
        userPassword,
        status,
        remarks,
        totals,
      } = form;

      this.createUsersInfoFunc(
        {
          nickName,
          avatar,
          userName,
          userPassword,
          status,
          remarks,
          totals,
        },
        done,
        loading
      );
    },

    //管理员信息修改
    rowUpdate(row, index, done, loading) {
      const { id, username, password, state } = row;
      this.updateAdminInfoApiFunc(
        { id, username, password, state },
        done,
        loading
      );
    },
    // 用户信息修改
    rowUpdateUsers(row, index, done, loading) {
      const {
        id,
        nickName,
        avatar,
        userName,
        userPassword,
        status,
        remarks,
        totals,
      } = row;
      this.updateUsersInfoApiFunc(
        {
          id,
          nickName,
          avatar,
          userName,
          userPassword,
          status,
          remarks,
          totals,
        },
        done,
        loading
      );
    },
    //删除管理员账户
    rowDel(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteAdminInfoApiFunc({ id: row?.id ?? "" });
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },

    //删除用户账户
    rowDelUsers(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteUsersInfoApiFunc({ id: row?.id ?? "" });
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },

    //
    handleClick(event) {
      console.log(event, "<==== handleClick");
    },

    /**
     * @name requests
     * @author --h28
     */
    // 获取主页
    async getHomePageInfoFunc() {
      this.main_table_loading = true;
      this.users_table_loading = true;
      //获取管理员账户
      const response = await queryAdminInfoApi({
        ...this.Main_search,
        currentPage: this?.Main_Page?.currentPage ?? 1,
        pageSize: this?.Main_Page?.pageSize ?? 10,
      }).catch(() => {});

      //获取前台用户账户
      const response2 = await queryUsersInfoApi({
        ...this.Users_search,
        currentPage: this?.Users_Page?.currentPage ?? 1,
        pageSize: this?.Users_Page?.pageSize ?? 10,
      }).catch(() => {});

      if (response?.code === 200 || response2?.code === 200) {
        this.Main_Data = response?.data?.records ?? [];
        this.Main_Page.total = response?.data?.total ?? 0;

        this.Users_Data = response2?.data?.records ?? [];
        this.Users_Page.total = response2?.data?.total ?? 0;
      }
      this.main_table_loading = false;
      this.users_table_loading = false;
    },
    // 新增管理员账户
    async createAdminInfoFunc(data, done, loading) {
      const response = await createAdminInfoApi(data).catch(() => {});
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "新增成功" });
        this.Main_Page.currentPage = 1;
        this.getHomePageInfoFunc();
        done();
      }
      loading();
    },
    // 新增用户账户
    async createUsersInfoFunc(data, done, loading) {
      const response = await createUsersInfoApi(data).catch(() => {});
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "新增成功" });
        this.Main_Page.currentPage = 1;
        this.getHomePageInfoFunc();
        done();
      }
      loading();
    },

    // 编辑管理员账户
    async updateAdminInfoApiFunc(data, done, loading) {
      const response = await updateAdminInfoApi(data).catch(() => {});
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "编辑成功" });
        this.getHomePageInfoFunc();
        done();
      }
      loading();
    },
    //编辑用户账户
    async updateUsersInfoApiFunc(data, done, loading) {
      const response = await updateUsersInfoApi(data).catch(() => {});
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "编辑成功" });
        this.getHomePageInfoFunc();
        done();
      }
      loading();
    },

    // 删除管理员账户
    async deleteAdminInfoApiFunc(data) {
      const loadding = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const response = await deleteAdminInfoApi(data).catch(() => {});
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "删除成功" });
        this.Main_Page.currentPage = 1;
        this.getHomePageInfoFunc();
      }
      loadding.close();
    },

    // 删除用户账户
    async deleteUsersInfoApiFunc(data) {
      const loadding = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const response = await deleteUsersInfoApi(data).catch(() => {});
      if (response?.code === 200) {
        this.$notify.success({ title: "提示", message: "删除成功" });
        this.Users_Page.currentPage = 1;
        this.getHomePageInfoFunc();
      }
      loadding.close();
    },

    //------------------------------------------------
    //用户购物车管理

    // 购物车管理
    shoppingCart(row) {
      console.log("购物车管理 - row: ", row);
      this.userId = row?.id ?? "";
      console.log("购物车管理 - usercartId: ", this.userId);
      this.getShoppingFunc();
    },

    // 搜索购物车商品
    async searchShoppingChange(params, done) {
      this.Shoppingcart_Page.currentPage = 1;
      this.Shoppingcart_Page.pageSize = 10;
      await this.getShoppingFunc();
      done();
    },
    currentShoppingChange(val) {
      this.Shoppingcart_Page.currentPage = val;
      this.getShoppingFunc();
    },

    sizeShoppingChange(val) {
      this.Shoppingcart_Page.pageSize = val;
      this.getShoppingFunc();
    },
    // 重置购物车商品搜索
    resetShoppingChange() {
      this.Shoppingcart_search = {};
    },
    // 刷新购物车商品主页
    refreshShoppingChange() {
      this.Shoppingcart_Page.currentPage = 1;
      this.getShoppingFunc();
    },

    // 获取购物车商品主页
    async getShoppingFunc() {
      console.log("获取购物车商品主页 - this.userId: ", this?.userId);
      if (!this?.userId) return;
      this.Shoppingcart_table_loading = true;    
      const response = await queryUsersCartApi({
        ...this.Shoppingcart_search,
        
        uid: this?.userId ?? "",
        currentPage: this?.Shoppingcart_Page?.currentPage ?? 1,
        pageSize: this?.Shoppingcart_Page?.pageSize ?? 10,
      }).catch(() => {});
      console.log(response, "<=========queryUsersCartApi");
      if (response?.code === 200) {
        //获取用户购物车商品数组
        // let _data = response?.data?.records?.length > 0 ? (response?.data?.records[0]?.products) : [];

        let _data = [];
        // 判断是否为空
        if(response?.data?.records?.length > 0 ) { _data = (response?.data?.records[0]?.products)}else { _data=[]}

        this.usercartId = response?.data?.records[0]?.id ?? "";
        console.log("获取购物车商品主页 - _data: ", _data);
        this.Shoppingcart_Data = _data ?? [];
        this.Shoppingcart_Page.total = response?.data?.total ?? 0;
        this.shoppingCartDrawer = true;
      }
      this.Shoppingcart_table_loading = false;
    },

    //更新用户购物车
    async rowUpdatecart(row, index,done,loading) {
      console.log("rowUpdatecart - Shoppingcart_Data: ", row);
      this.productId = row?.id ?? "";
      this.productNum = row?.pcount ?? 1;

      console.log("rowUpdatecart - this.usercartId: ", this?.usercartId);
        console.log("rowUpdatecart - this.productId: ", this?.productId);
      console.log("rowUpdatecart - this.productNum: ", this?.productNum);
        if(this?.productNum<=0){
           this.$message.error("数量不能小于0");
           loading();
          return;
        }
      const response = await updateUsersCartApi({
        
        // ...this.Shoppingcart_search,
        sid : this.usercartId,
        pid : this.productId,
        pcount : this?.productNum ?? 1,

    }).catch(() => {});
      if (response?.code === 200) {
        console.log("rowUpdatecart - data:==========> ", response);
        this.$message.success("修改成功");
        this.shoppingCartDrawer = true;
      }
      this.getShoppingFunc();
      done();
    },


    //移除购物车商品
    removeProducts() {},
  },
};
</script>

<!-- <style>

  </style> -->
